package com.lovol.gis.demo.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.locationtech.jts.geom.Coordinate;

import java.util.List;

public class GeometryUtil {

    public static Coordinate [] parseCoord(String points){
        JSONArray jsonArray = JSON.parseArray(points);
        int size = jsonArray.size();
        Coordinate [] coordinates = new Coordinate[size+1];

        for (int i = 0; i < size; i++) {
            JSONArray arr = (JSONArray) jsonArray.get(i);
            Double lon = Double.parseDouble(arr.get(0).toString());
            Double lat = Double.parseDouble(arr.get(1).toString());
            Coordinate coordinate = new Coordinate(lon, lat);
            coordinates[i]=coordinate;
        }
        return coordinates;
    }

    public static String pointWktString(double x, double y) {
        String geoStr = "POINT" + "(" + x + " " + y + ")";
        return geoStr;
    }

    /**
     * 由线坐标串构造WKT对象
     *
     * @param coords
     * @return
     */
    public static String lineWktString(Coordinate[] coords) {
        StringBuilder geoStr = new StringBuilder();
        geoStr.append("LINESTRING(");
        for (Coordinate coord : coords) {
            geoStr.append(coord.getX()).append(" ").append(coord.getY()).append(",");
        }
        geoStr.delete(geoStr.length() - 1, geoStr.length());
        geoStr.append(")");
        return geoStr.toString();
    }

    public static String multiPolygonWktString(List<Coordinate> coords) {
        StringBuilder builder = new StringBuilder();
        builder.append("MULTIPOLYGON(((");
        for (Coordinate coord : coords) {
            builder.append(coord.getX()).append(" ").append(coord.getY()).append(",");
        }
        builder.append(coords.get(0).getX()).append(" ").append(coords.get(0).getY()).append(")))");

        return builder.toString();
    }

    public static String extentWkt(double minX,double minY,double maxX,double maxY) {
        StringBuilder builder = new StringBuilder();
        builder.append("POLYGON((")
                .append(minX).append(" ").append(minY).append(",")
                .append(maxX).append(" ").append(minY).append(",")
                .append(maxX).append(" ").append(maxY).append(",")
                .append(minX).append(" ").append(maxY).append(",")
                .append(minX).append(" ").append(minY).append("))");

        return builder.toString();
    }

    public static String polygonWktString(List<Coordinate> coords) {
        StringBuilder builder = new StringBuilder();
        builder.append("POLYGON((");
        for (Coordinate coord : coords) {
            builder.append(coord.getX()).append(" ").append(coord.getY()).append(",");
        }
        builder.append(coords.get(0).getX()).append(" ").append(coords.get(0).getY()).append("))");

        return builder.toString();
    }
}
